package com.zxe.freshserver.controller.user;

import com.zxe.commonserver.result.Result;
import com.zxe.freshserver.pojo.FreshVO;
import com.zxe.freshserver.service.FreshService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 生鲜管理
 */
@RestController("userFreshController")
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户端生鲜相关接口")
public class FreshController {

    @Autowired
    private FreshService freshService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询生鲜
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询生鲜")
    public Result<List<FreshVO>> findByCategoryId(@RequestParam Long categoryId) {
        log.info("根据分类id查询生鲜：{}", categoryId);
        //构造redis中的key，fresh_分类id
        String key = "fresh_" + categoryId;
        //查询redis中是否存在生鲜数据
        ValueOperations valueOperations1 = redisTemplate.opsForValue();
        List<FreshVO> list = (List<FreshVO>) valueOperations1.get(key);
        if (list != null && list.size() > 0) {
            //如果缓存中存在，则直接返回
            return Result.success(list);
        }

        //如果不存在，就去查询数据库，并将查询到的数据放入redis中
        list = freshService.findByCategoryId(categoryId);
        ValueOperations valueOperations2 = redisTemplate.opsForValue();
        valueOperations2.set(key, list);
        return Result.success(list);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询生鲜")
    public FreshVO findById(@PathVariable Long id) {
        FreshVO freshVO = freshService.findById(id);
        return freshVO;
    }

}
